<template>
  <el-input
    ref="input"
    v-model="value"
    size="small"
    class="cell-editor"
    :max-length="params.colDef.maxLength"
    :placeholder="params.colDef.placeholder"
    :allow-clear="params.colDef.allowClear"
    @change="change"
    @input="input"
  />
</template>

<script>
const KEY_BACKSPACE = 8 // ESC键
const KEY_DELETE = 46 // Delete键

export default {
  name: 'StringInputCellEditor',
  data() {
    return {
      value: ''
    }
  },
  created() {
    this.setInitialState(this.params)
  },
  mounted() {
    if (!this.params.cellStartedEdit) return
    this.$nextTick(() => {
      const input = this.$refs.input
      input.focus()
      // 选中值
      if (this.highlightAllOnFocus) {
        input.$refs.input &&
          input.$refs.input.select()
        this.highlightAllOnFocus = false
      }
    })
  },
  methods: {
    getValue() {
      return this.value
    },
    focusIn() {
      const input = this.$refs.input
      input.focus()
      input.$refs.input &&
      input.$refs.input.select()
    },
    // 默认值
    setInitialState(params) {
      let startValue
      let highlightAllOnFocus = true
      if (params.keyPress === KEY_BACKSPACE || params.keyPress === KEY_DELETE) {
        startValue = ''
      } else if (params.charPress) {
        startValue = params.charPress
        highlightAllOnFocus = false
      } else {
        startValue = params.value
      }

      if (this.value !== startValue) {
        if (this.params.change) {
          this.params.change(this.params.node, startValue)
        }
      }
      this.value = startValue
      this.highlightAllOnFocus = highlightAllOnFocus
    },
    // 修改事件
    change() {
      if (this.params.change) {
        this.params.change(this.params.node, this.value)
      }
    },
    input() {
      if (this.params.input) {
        this.params.input(this.params.node, this.value)
      }
    }
  }
}
</script>

<style less="scss" scoped>
</style>
